package cn.unknowpupil.init.service.system.impl;

import cn.unknowpupil.init.exceptions.HealthException;
import cn.unknowpupil.init.properties.FileProperties;
import cn.unknowpupil.init.service.system.ICommonService;
import cn.unknowpupil.init.utils.file.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * Created at 2020/11/5 by w10g <br>
 * Initialize CommonServiceImpl ... <br>
 *
 * @author unknowpupil
 * @since 0.0.1
 */
@Service

public class CommonServiceImpl implements ICommonService {
    @Autowired
    private FileProperties fileProperties;

    @Override
    public String uploadAvatar(MultipartFile avatarFile) {
        int fileNamelength = avatarFile.getOriginalFilename().length();
        if (fileNamelength > fileProperties.getAvatarMaxSize()) {
            throw new HealthException("如果超出最大大小");
        }
        String upload = null;
        try {
            upload = FileUtils.upload(fileProperties.getPath().getAvatar(), avatarFile);
        } catch (IOException e) {
            throw new HealthException("图片上传失败");
        }
        String path = FileUtils.subStringPath(fileProperties.getPath().getAvatar());

        return path+upload;
    }

    @Override
    public String uploadFile(MultipartFile file) {
        int fileNamelength = file.getOriginalFilename().length();
        if (fileNamelength > fileProperties.getMaxSize()) {
            throw new HealthException("如果超出最大大小");
        }
        String upload = null;
        try {
            upload = FileUtils.upload(fileProperties.getPath().getPath(), file);
        } catch (IOException e) {
            throw new HealthException("文件上传失败");
        }
        String path = FileUtils.subStringPath(fileProperties.getPath().getPath());

        return path+upload;
    }
}
